/**
 * Copyright (c) 2015-2018, 新疆广电网络股份有限公司 All Rights Reserved.
 */
package com.xjnt.frameworks.web.render;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.shiro.SecurityUtils;

import com.jfinal.render.Render;
import com.octo.captcha.service.CaptchaServiceException;
import com.xjnt.frameworks.web.jcaptcha.JCaptcha;

/**
 * @author caoyong
 *
 */
public class JCaptchaRender extends Render {
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jfinal.render.Render#render()
	 */
	@Override
	public void render() {
		try {
			response.setDateHeader("Expires", 0L);
			response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			response.addHeader("Cache-Control", "post-check=0, pre-check=0");
			response.setHeader("Pragma", "no-cache");
			response.setContentType("image/jpeg");

			String id = SecurityUtils.getSubject().getSession(true).getId().toString();
			System.out.println("验证码:" + id);
			BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);

			ServletOutputStream out = response.getOutputStream();

			ImageIO.write(bi, "jpg", out);
			try {
			    out.flush();
			} finally {
			    out.close();
			}
		} catch (CaptchaServiceException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
